package com.example.exercise.rule;

import com.example.exercise.common.Pojo;
import com.example.exercise.rule.vo.RuleDemo;
import org.mvel2.MVEL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MVELUtils {

    public static void main(String[] args) {
        BigDecimal a = new BigDecimal("1.0232");
        BigDecimal b = new BigDecimal("5.362126");
        System.err.println(a.multiply(b));
        RuleDemo demo = new RuleDemo();
        demo.setA(a);
        demo.setB(b);
        System.err.println(DroolsUtils.calculate(demo, "result.add(data.getA().multiply(data.getB()));", null, null));
        MVEL.eval("System.err.println(a.multiply(b));", demo);
    }
    private static final Logger LOGGER = LoggerFactory.getLogger(MVELUtils.class);

    public static <T extends Pojo> Boolean match(T data, String ruleStr){
        String ruleExp = DataInit.preHandler(data, ruleStr);
        if(ruleExp == null || "".equals(ruleExp)){
            LOGGER.error("规则表达式错误");
            return false;
        }
        String finalRule = DataInit.transExpWithSubDateField(data, ruleExp);
        Map<String, Object> map = DataInit.dataToMap(data, "yyyy-MM-dd");
        return MVEL.evalToBoolean(finalRule, map);
    }

    public static <T extends Pojo> List<T> match(List<T> dataList, String ruleStr){
        if(dataList.isEmpty()){
            LOGGER.error("规则表达式错误，返回所有数据");
            return dataList;
        }
        T data = dataList.get(0);
        String ruleExp = DataInit.preHandlerForList(data, ruleStr);
        if(ruleExp == null){
            LOGGER.error("规则表达式错误，返回所有数据");
            return dataList;
        }

        String finalRule = DataInit.transExpWithDateField(data, ruleExp, "item.");
        Map<String, Object> map = new HashMap<>();
        map.put("list", dataList);
        List<T> results = new ArrayList<>();
        map.put("results", results);
        MVEL.eval("for(item : list){\n" +
                "    if(" + finalRule + "){\n" +
                "        results.add(item);\n" +
                "    }\n" +
                "}", map);
        return results;
    }

    public static <T extends Pojo> List<Object> calculate(T data, String ruleStr){
        List<Object> results = new ArrayList<>();
        Map<String, Object> map = DataInit.dataToMap(data, "yyyy-MM-dd");
        map.put("results", results);
        MVEL.eval(ruleStr, map);
        return results;
    }

    public static <T extends Pojo> List<Object> calculate(List<T> dataList, String ruleStr){
        List<Object> results = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("results", results);
        map.put("list", dataList);
        MVEL.eval(ruleStr, map);
        return results;
    }

}
